package com.hjq.fcloud.utils

import android.content.Context
import android.graphics.Bitmap
import android.media.ThumbnailUtils
import android.provider.MediaStore
import android.util.Log
import java.io.File
import java.io.FileOutputStream

object VideoThumbnailUtil {

    private const val TAG = "VideoThumbnailUtil"

    /**
     * 从视频文件中获取缩略图并保存为文件
     *
     * @param videoPath 视频文件的路径
     * @param outputPath 缩略图保存的路径
     * @return 如果保存成功，返回缩略图的路径；否则返回null
     */
    fun getVideoThumbnail(context: Context, videoPath: String, outputPath: String? = null): String? {
        if (videoPath.isNullOrEmpty()) {
            return null
        }
        var finalOutputPath = outputPath
        if (finalOutputPath == null) {
            //为空的默认路径
            finalOutputPath = context.getCacheDir().absolutePath + "_VideoThumbnail_" + FileUtils.getFileName2(videoPath)+".png"
        }

        var bitmap: Bitmap? = null
        try {
            bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND)
            if (bitmap != null) {
                // 将Bitmap保存到文件
                val outputFile = File(finalOutputPath)
                if (outputFile.exists()) {
                    outputFile.delete()
                }
                outputFile.createNewFile()

                val out = FileOutputStream(outputFile)
                // 将Bitmap压缩为PNG格式并保存到文件
                // 你也可以选择其他格式，比如JPEG
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
                out.flush()
                out.close()
                return outputFile.absolutePath
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "Error retrieving thumbnail", e)
        } finally {
            // 释放资源
            bitmap?.recycle()
        }

        return null
    }
}